let userList = [
    {
        username: 'koa1',
        password: '12345',
        datetime: '2020-03-22'
    },
    {
        username: 'koa',
        password: '12345',
        datetime: '2020-03-23'
    }
]

let hasUser = (username) => userList.map((item) => item.username).includes(username);

module.exports = {
    'POST /api/login': async (ctx, next) => {
        let username = ctx.request.body.username || '',
            password = ctx.request.body.password || '';


        if (!hasUser(username)) {
            ctx.rest({
                code: -1,
                msg: '当前用户不存在'
            })
            return;
        }

        let _password = userList.filter(item => item.username === username)[0].password;

        if (hasUser(username) && password === _password) {
            ctx.rest({
                code: 0,
                msg: '登录成功'
            });
        } else {
            ctx.rest({
                code: -1,
                msg: '登录失败'
            });
        }
    },
    'POST /api/register': async (ctx, next) => {
        let username = ctx.request.body.username || '',
            password = ctx.request.body.password || '';

        if (hasUser(username)) {
            ctx.rest({
                code: -1,
                msg: '当前用户已存在'
            })
            return;
        }

        userList.unshift({
            username,
            password,
            datetime: '2020-03-26'
        });
        ctx.rest({
            code: 0,
            msg: '注册成功'
        })
    },
    'GET /api/user/getUserList': async (ctx, next) => {
        ctx.rest({
            code: 0,
            data: userList
        });
    },
    'POST /api/user/deleteUser': async (ctx, next) => {
        let username = ctx.request.body.username || '';
        userList = userList.filter(item => (item.username !== username));
        console.log(userList)

        ctx.rest({
            code: 0,
            msg: '删除成功'
        });
    },
    'POST /api/user/updateUser': async (ctx, next) => {
        let username = ctx.request.body.username || '',
            password = ctx.request.body.password || '';


        userList.map(item => {
            if (item.username === username) {
                item.password = password
            }
        })

        ctx.rest({
            code: 0,
            msg: '更新成功'
        });
    },
}